package net.jalbum.filters.arty.effects;

import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.awt.image.DataBuffer;
import java.util.Map;

/**
 *
 * @author Sarah Schölzel 
 */
public class TulipFilter extends ArtySupport {

    private int[] pixels;

    public TulipFilter() {
    }

    @Override
    public String getName() {
        return "Tuilp";
    }

    @Override
    public String getDescription() {
        return "effect like the Hefe filter in Instagram";
    }

    @Override
    public BufferedImage filter(BufferedImage bi, Map map) {
        return filter(bi);
    }

    @Override
    public BufferedImage filter(BufferedImage bi) {
        bi = super.filter(bi);

        BufferedImage dstImg = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());

        //Copy Image: more red,more yellow(= less blue)
        initPixelsArray(bi);
        int[] changedPixels = changeColor();
        BufferedImage changedColor = new BufferedImage(bi.getWidth(), bi.getHeight(), bi.getType());
        changedColor.setRGB(0, 0, bi.getWidth(), bi.getHeight(), changedPixels, 0, bi.getWidth());

        //Brightness and Contrast
        bi = applyBrightnessAndContrast(bi, -20, 20);

        //Blending Mode: Color, 50%
        Graphics2D gdst = dstImg.createGraphics();
        gdst.drawImage(bi, 0, 0, null);
        gdst.setComposite(BlendComposite.getInstance(BlendComposite.BlendingMode.COLOR, 0.5f));
        gdst.drawImage(changedColor, 0, 0, bi.getWidth(), bi.getHeight(), null);

        //Border
        dstImg = adjustBorder(dstImg);

        return dstImg;
    }

    /**
     * takes the pixels from a BufferedImage and stores them in an array
     */
    private void initPixelsArray(BufferedImage image) {
        int width = image.getWidth();
        int height = image.getHeight();
        pixels = new int[width * height];
        image.getRGB(0, 0, width, height, pixels, 0, width);

    }

    /**
     * changes the color of the image - more red and less blue
     * @return new pixel array
     */
    private int[] changeColor() {
        int[] changedPixels = new int[pixels.length];
        double frequenz = 2 * Math.PI / 1020;

        for (int i = 0; i < pixels.length; i++) {
            int argb = pixels[i];
            int a = (argb >> 24) & 0xff;
            int r = (argb >> 16) & 0xff;
            int g = (argb >> 8) & 0xff;
            int b = argb & 0xff;

            r = (int) (255 * Math.sin(frequenz * r));
            b = (int) (-255 * Math.cos(frequenz * b) + 255);

            changedPixels[i] = (a << 24) | (r << 16) | (g << 8) | b;
        }

        return changedPixels;
    }
}
